//
//  OAuthViewController.swift
//  sinaweibo
//
//  Created by mac on 15/11/11.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount() {
    
        let jsString = "document.getElementById('userId').value = '544745729@qq.com' ,document.getElementById('passwd').value = 'ym544745729!?'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        setupUI()
        
        loadOauthPage()
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
    
        SVProgressHUD.dismiss()
    }

    private func loadOauthPage() {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setupUI(){
    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }

}

extension OAuthViewController: UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        

        guard let urlString = request.URL?.absoluteString else {
            return false
        }

        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        guard let query = request.URL?.query else {
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)

        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            if error != nil {
            
                SVProgressHUD.showErrorWithStatus("请检查网络")
            }
            self.dismissViewControllerAnimated(true, completion: nil)
            NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "welcome")
        }
        
        return true
    }
}
